<?php
class UsersController extends AppController {

	var $name = 'Users';
	
	public $components = array('Recaptcha');
	
	function beforeFilter() {
		$this->Auth->allow('login', 'logout', 'add', 'request_username_reminder', 'request_password_reset', 'password_reset');
        $this->Recaptcha->publickey = "6LdbILsSAAAAAPwfWfCAOXv3ubSym2q4ykYCPsw9";
        $this->Recaptcha->privatekey = "6LdbILsSAAAAAHSdBLdMthf4qCgnc8fhdhb-55HK";
		parent::beforeFilter();
	}

	function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}

	function add() {
        if (!empty($this->data)) {
            if ($this->Recaptcha->valid($this->params['form'])) {
                $this->User->create();
                if ($this->data['User']['member_id'] != -1) {
                    if ($this->User->save($this->data)) {
                        $this->Session->setFlash(__('The user has been saved', true));
                        $this->redirect('/');
                    } else {
                        unset($this->data['User']['password']);
                        unset($this->data['User']['password_confirm']);
                        $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
                    }
                } else {
                    $db =& ConnectionManager::getDataSource($this->User->useDbConfig);
                    $db->begin($this->User);
                    if ($this->User->Member->save($this->data)) {
                        $this->data['User']['member_id'] = $this->User->Member->id;
                        if ($this->User->save($this->data)) {
                            $db->commit($this->User);
                            $this->Session->setFlash(__('The user has been saved', true));
                            $this->redirect('/');
                        } else {
                            $db->rollback($this->User);
                            unset($this->data['User']['password']);
                            unset($this->data['User']['password_confirm']);
                            $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
                        }
                    } else {
                        $db->rollback($this->User);
                        unset($this->data['User']['password']);
                        unset($this->data['User']['password_confirm']);
                        $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
                    }
                }
            } else {
                unset($this->data['User']['password']);
                unset($this->data['User']['password_confirm']);
                $this->set('reCaptchaFailed', true);
                $this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
            }
        }
		$members = array('' => '') + array('-1' => '*New Member') + $this->User->Member->find('list', array('conditions' => array('Member.id NOT IN (SELECT DISTINCT member_id FROM users WHERE member_id IS NOT NULL)'), 'order' => 'name'));
		$group = $this->User->Group->findByName('Members');
		$locations = $this->User->Member->Location->find('list');
		$this->data['User']['group_id'] = $group['Group']['id'];
		$this->set(compact('members', 'groups', 'locations'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The user has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
		$members = $this->User->Member->find('list');
		$groups = $this->User->Group->find('list');
		$this->set(compact('members', 'groups'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for user', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->delete($id)) {
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('User was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
    
    function request_username_reminder() {
        if (!empty($this->params['data'])) {
            $user = $this->User->findByEmail($this->data['User']['email']);
            
            if (empty($user)) {
                $this->Session->setFlash(__('That email could not be found.', true));
            } else {
                $to = $user['User']['email'];
                $subject = 'PIMP Username Reminder';
                $message = "Your registered username is: {$user['User']['username']}";
                $from = 'noreply@' . $_SERVER['SERVER_NAME'];
                $headers = "From: $from\n" .
                    "Reply-To: $from\n" .
                    "X-Mailer: CakePHP PHP " . phpversion() . "\n" .
                    "Content-Type: text/plain; charset=ISO-8859-1";
                
                if (mail($to, $subject, $message, $headers)) {
                    $this->Session->setFlash('A username reminder email was sent. Please check your inbox.');
                } else {
                    $this->Session->setFlash('Server error, please try again later.');
                }
                $this->redirect('/');
            }
        }
    }
    
    function request_password_reset() {
        if (!empty($this->params['data'])) {
            $user = $this->User->findByEmail($this->data['User']['email']);
            
            if (empty($user)) {
                $this->Session->setFlash(__('That email could not be found.', true));
            } else {
                $ticket = md5($user['User']['email'] . $user['User']['password'] . Configure::read('Security.salt'));
                $to = $user['User']['email'];
                $subject = 'PIMP Password Reset Link';
                $message = 'http://' . $_SERVER['SERVER_NAME'] . '/' . $this->params['controller'] . '/password_reset/' . $ticket;
                $from = 'noreply@' . $_SERVER['SERVER_NAME'];
                $headers = "From: $from\n" .
                    "Reply-To: $from\n" .
                    "X-Mailer: CakePHP PHP " . phpversion() . "\n" .
                    "Content-Type: text/plain; charset=ISO-8859-1";
                
                if (mail($to, $subject, $message, $headers)) {
                    $this->Session->setFlash('A recovery email was sent. Please check your inbox.');
                } else {
                    $this->Session->setFlash('Server error, please try again later.');
                }
                $this->redirect('/');
            }
        }
    }
	
	function password_reset($hash = null) {
        
        if (!empty($this->data)) {
            $user = $this->User->find('first', array('conditions' => array("MD5(CONCAT(User.email, User.password, '" . Configure::read('Security.salt') . "'))" => $hash)));
            if (empty($this->data)) {
                $this->Session->setFlash('Invalid recover link, invalid hash.');
                $this->redirect('/');
            }
            $this->data['User']['id'] = $user['User']['id'];
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('Your password has been updated', true));
                $this->redirect(array('action' => 'login'));
            } else {
                unset($this->data['User']['password']);
                unset($this->data['User']['password_confirm']);
                $this->Session->setFlash(__('The password could not be saved. Please, try again.', true));
            }
        } else if (!empty($hash)) {
            $this->data = $this->User->find('first', array('conditions' => array("MD5(CONCAT(User.email, User.password, '" . Configure::read('Security.salt') . "'))" => $hash)));
            if (empty($this->data)) {
                $this->Session->setFlash('Invalid recover link, invalid hash.');
                $this->redirect('/');
            }
            unset($this->data['User']['password']);
	    } else {
            $this->Session->setFlash('Invalid recover link, missing hash.');
            $this->redirect('/');
	    }
        $this->set('hash', $hash);
	}

	/**
	 *  The AuthComponent provides the needed functionality
	 *  for login, so you can leave this function blank.
	 */
	function login() {
	}

	function logout() {
		$this->redirect($this->Auth->logout());
	}
}
?>